package ext.tianma.util;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.util.Enumeration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import ext.tianma.workflow.BomWorkFlowUtil;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.log4j.LogR;
import wt.org.OrganizationServicesHelper;
import wt.org.WTUser;
import wt.project.Role;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.engine.WfProcess;

public class GetSuperior {
	/** Log4j Logger. */
	private static final Logger LOGGER = LogR.getLogger(GetSuperior.class.getName());
	private static DefaultHttpClient client;
	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	/**
	 * 获得业务上级返回业务上级name
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 * 
	 */
	public static String getSuperior(String name) throws Exception {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrl = ut.getValueByKey("erdp.url");
		String erdpurl = erdpUrl + "/tmrdp/v1/user/higherLevel?name=" + name;
		LOGGER.debug("erdpurl11111111111111" + erdpurl);
		String returnstr = "";
		try {
			// {"success":true,"code":"200","message":"success","res":{"data":{"higherLevel":"eee"}}}
			returnstr = sendXMLDataByGet(erdpurl);
			LOGGER.debug("sendXMLDataByGet.........." + returnstr);
			JSONObject obj;
			if (StringUtils.isNotEmpty(returnstr)) {// 返回数据不能为空
				obj = new JSONObject(returnstr);
				if (obj.has("success")) {
					boolean flag = obj.getBoolean("success");
					if (flag) {
						// {"data":{"higherLevel":"eee"}}
						JSONObject obj2 = new JSONObject(obj.getString("res"));
						// {{"higherLevel":"eee"}
						String data = obj2.getString("data");
						JSONObject obj3 = new JSONObject(data);
						// {{"higherLevel":"eee"}
						String higherLevel = obj3.getString("higherLevel");
						LOGGER.debug("===higherLevel===:" + higherLevel);
						returnstr = higherLevel;
					} else {
						returnstr = "fail";
					}
				}
			} else {
				returnstr = "fail";
			}

		} catch (Exception e) {
			returnstr = "fail";
			e.printStackTrace();
		}
		LOGGER.debug("getSuperior..........." + returnstr);
		return returnstr;
	}

	/**
	 * 给EE主管添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @param user
	 */
	public static String putDirectorUser(ObjectReference self, String internal_value) {
		String result = "";
		try {
			WfProcess process = BomWorkFlowUtil.getProcess(self);
			String name = getSuperior(process.getCreator().getName());
			LOGGER.debug("name----------" + name);

			if ("fail".equals(name)) {
				return "fail";
			} else {
				WTUser wtUser = getUserFromName(name);
				LOGGER.debug("wtUser------------" + wtUser);
				addPrincipalToRole(self, internal_value, wtUser);
				return "succeed";
			}
		} catch (Exception e) {
			result = "fail";
			e.printStackTrace();
		}
		LOGGER.debug("putDirectorUser..........." + result);
		return result;
	}

	/**
	 * 给EE经理添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @param user
	 * @throws Exception
	 */
	public static String putManagerUser(ObjectReference self, String internal_value) {
		String result = "";
		try {
			WfProcess process = BomWorkFlowUtil.getProcess(self);
			String name = getSuperior(process.getCreator().getName());
			String name2 = getSuperior(name);
			if (!"fail".equals(name) && !"fail".equals(name2)) {
				WTUser wtUser = getUserFromName(name2);
				addPrincipalToRole(self, internal_value, wtUser);
				return "succeed";
			} else {
				return "fail";
			}
		} catch (Exception e) {
			result = "fail";
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 给角色添加用户
	 * 
	 * @param self
	 * @param internal_value
	 * @param user
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 */
	public static void addPrincipalToRole(ObjectReference self, String internal_value, WTUser user)
			throws WTPropertyVetoException, WTException {
		WfProcess process = BomWorkFlowUtil.getProcess(self);
		wt.team.Team team = null;
		try {
			team = getTeam(process);
			LOGGER.debug("team------" + team);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new WTException(ex);
		}

		Role theRole = Role.toRole(internal_value);
		LOGGER.debug("theRole---------" + theRole);
		if (user == null) {
			throw new WTException("没有找到用户: [" + user + "] ");
		} else {
			team.addPrincipal(theRole, user);
		}
		PersistenceHelper.manager.refresh(team);
	}

	/**
	 * 根据用户名得到用户
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 */
	public static WTUser getUserFromName(String name) throws WTException {
		Enumeration enumUser = OrganizationServicesHelper.manager.findUser(WTUser.NAME, name);
		WTUser user = null;
		if (enumUser.hasMoreElements())
			user = (WTUser) enumUser.nextElement();

		if (user == null) {
			enumUser = OrganizationServicesHelper.manager.findUser(WTUser.FULL_NAME, name);
			if (enumUser.hasMoreElements())
				user = (WTUser) enumUser.nextElement();
		}

		if (user == null) {
			throw new WTException("系统中不存在用户名为'" + name + "'的用户！");
		}

		return user;
	}

	/**
	 * 根据WfProcess对象，获得团队
	 * 
	 * @param process
	 * @return
	 * @throws Exception
	 */
	public static Team getTeam(WfProcess process) throws Exception {

		Team team = null;
		ReferenceFactory rf = new ReferenceFactory();
		String oid = rf.getReferenceString(process);
		WTObject wtobject = (WTObject) rf.getReference(oid).getObject();
		if (wtobject instanceof TeamManaged) {
			team = (Team) ((TeamManaged) wtobject).getTeamId().getObject();
		} else if (wtobject instanceof Team) {
			team = (Team) wtobject;
		}
		return team;
	}

	/**
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String sendXMLDataByGet(String url) {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String key = ut.getValueByKey("erdp.key");
		String value = ut.getValueByKey("erdp.value");
		String result = "";
		try {
			if (client == null) {
				client = new DefaultHttpClient();
				// String ssl = enableSSL(client);
				enableSSL(client);
				LOGGER.debug("enableclient..............." + client);
			}
			client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

			LOGGER.debug("sendXMLDataByGet......" + client);
			HttpGet get = new HttpGet(URLDecoder.decode(url));
			get.setHeader("Content-Type", "application/json;charset=UTF-8");
			get.setHeader(key, value);
			get.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
			get.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
			get.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
			get.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);
			// 打印请求信息
			LOGGER.debug("HttpUtils 打印请求信息" + get.getRequestLine());
			HttpResponse httpResponse = client.execute(get);
			// 打印响应信息
			LOGGER.debug("HttpUtils 打印响应信息" + httpResponse.getStatusLine());
			// HttpStatus.SC_OK==200
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(httpResponse.getEntity());
			}
		} catch (ClientProtocolException e) {
			LOGGER.debug("HttpUtilsClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			LOGGER.debug("HttpUtilsIOException");
			e.printStackTrace();
		}
		LOGGER.debug("sendXMLDataByGet........" + result);
		return result;

	}

	/**
	 * 
	 * @param xml
	 * @return
	 */
	public static String getUTF8XMLString(String xml) {
		StringBuffer sb = new StringBuffer();
		sb.append(xml);
		String xmString = "";
		try {
			xmString = URLEncoder.encode(sb.toString(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		return xmString.toString();
	}

	/**
	 * 访问https的网站
	 * 
	 * @param httpclient
	 */
	private static void enableSSL(DefaultHttpClient httpclient) {
		// 调用ssl
		// String res = "";
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);
			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme https = new Scheme("https", sf, 443);
			httpclient.getConnectionManager().getSchemeRegistry().register(https);
		} catch (Exception e) {
			// res = "fail";
			e.printStackTrace();
		}
		// return res;
	}

	/**
	 * 重写验证方法，取消检测ssl
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {
		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
				throws CertificateException {
		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	};
}
